﻿using System.Collections;
using System.Collections.Generic;
using LitJson;
using UnityEngine;
using UnityEngine.UI;

public class ChatPanel : BasePanel
{

	public Text nickText;

	public Button closeBtn;

	public InputField msgInputField;

	public Button sendBtn;

	private ChatVO _chatVo;

	private GameObject _msgItemGoPrefab;

	private SendMsgRequest _sendMsgRequest;

	public ChatVO ChatVo
	{
		get { return _chatVo; }
		set { _chatVo = value; }
	}

	// Use this for initialization
	void Start () {
		
		//组件初始化
		_msgItemGoPrefab = Resources.Load<GameObject>("UIPanel/MsgItem");
		_sendMsgRequest = this.gameObject.GetComponent<SendMsgRequest>();
		
		
		//按钮事件函数绑定
		closeBtn.onClick.AddListener(delegate { CloseButtonClicked(); });
		sendBtn.onClick.AddListener(delegate { SendButtonClicked(); });
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}

	
	private void CloseButtonClicked()
	{
		//pop掉当前Panel
		UnityFacade.Instance.UiManager.PopPanel();
		
	}

	private void SendButtonClicked()
	{
		// 执行SendMsg请求
		_sendMsgRequest.SendRequest(_chatVo.ChatId,msgInputField.text);
		
		
	}

	
	/// <summary>
	/// 刷新显示（外界调用）
	/// </summary>
	public void SyncShow()
	{
		nickText.text = _chatVo.Nick;
		//todo 现有MsgItem进行销毁
		GameObject[] msgItemGos = GameObject.FindGameObjectsWithTag("MsgItem");
		foreach (GameObject msgItemGo in msgItemGos)
		{
			Destroy(msgItemGo);
		}
		
		
		//todo 处理双方头像的加载
		HttpTool.Instance.GetImageConvertToSpriteByURL(UnityFacade.Instance.ApplicationManager.ActiveUser.Avatar,"local");
		HttpTool.Instance.GetImageConvertToSpriteByURL(_chatVo.Avatar,"opponent");


		StartCoroutine(InitImageForSprite());




	}
	
	//UI框架相关生命周期函数
	public override void OnEnter()
	{
		if (this.gameObject.activeSelf == false)
		{
			this.gameObject.SetActive(true);
		}
	}

	public override void OnPause()
	{
		this.gameObject.SetActive(false);
	}

	public override void OnResume()
	{
		if (this.gameObject.activeSelf == false)
		{
			this.gameObject.SetActive(true);
		}
	}

	public override void OnExit()
	{
		this.gameObject.SetActive(false);
		//将HttpTool暂存的Sprite置为null
		HttpTool.Instance.ClearSprite("all");
		
	}

	/// <summary>
	/// 处理发送消息的响应
	/// </summary>
	/// <param name="respJsonData"></param>
	public void HandleSendMsgResponse(JsonData respJsonData)
	{
		if (respJsonData["state"].Equals("success"))
		{
			//实例化MsgItem(自己发的消息必定在右边)
			MsgDO msgDo =new MsgDO();
			msgDo.ActiveAvatar = "right";
			msgDo.Content = respJsonData["data"]["content"].ToString();
			msgDo.ReceiveTime = respJsonData["data"]["time"].ToString();
			
				
			//寻找挂在点
	
			Transform v_layoutPos = UnityFacade.Instance.UiManager.InstantiatedPanelDict[PanelType.Chat].transform
				.Find("Panel_Center/V_Layout").transform;

			GameObject msgItemGo = GameObject.Instantiate(_msgItemGoPrefab, v_layoutPos, false);
			MsgItem msgItem = msgItemGo.GetComponent<MsgItem>();
			msgItem.MsgDo = msgDo;
			msgItem.SyncShow();



		}else if (respJsonData["state"].Equals("fail"))
		{
			Debug.LogError(respJsonData["msg"]);
			MsgPanel msgPanel =(MsgPanel) UnityFacade.Instance.UiManager.PushPanel(PanelType.Msg);
			msgPanel.SyncShow("fail",respJsonData["msg"].ToString());
		}
	}
	
	/// <summary>
	/// 处理接收消息的响应
	/// </summary>
	/// <param name="respJsonData"></param>
	/// <exception cref="NotImplementedException"></exception>
	public void HandleReceiveMsgResponse(JsonData respJsonData)
	{
		Debug.Log(respJsonData["msg"]);
		
		MsgDO msgDo =new MsgDO();
		msgDo.ActiveAvatar = "left";//接收的消息都生成在左边
		msgDo.Content = respJsonData["data"]["content"].ToString();
		msgDo.ReceiveTime = respJsonData["data"]["time"].ToString();
		//寻找挂在点
	
		Transform v_layoutPos = UnityFacade.Instance.UiManager.InstantiatedPanelDict[PanelType.Chat].transform
			.Find("Panel_Center/V_Layout").transform;

		GameObject msgItemGo = GameObject.Instantiate(_msgItemGoPrefab, v_layoutPos, false);
		MsgItem msgItem = msgItemGo.GetComponent<MsgItem>();
		msgItem.MsgDo = msgDo;
		msgItem.SyncShow();
		
		
	}
	
	
	private IEnumerator InitImageForSprite()
	{
		//todo 可以开启一个等待动画的显示
        
		while (HttpTool.Instance.LocalSprite == null||HttpTool.Instance.OpponentSprite==null)
		{
			yield return new WaitForFixedUpdate();
		}
		
		//寻找挂在点

		Transform v_layoutPos = UnityFacade.Instance.UiManager.InstantiatedPanelDict[PanelType.Chat].transform
			.Find("Panel_Center/V_Layout").transform;
		
		//  历史消息的生成  (若有)
		if (_chatVo.HistoryMsg != null && !_chatVo.HistoryMsg.Equals("[]"))
		{
			
			//todo 预制体msgItem可能尚未来得及,再次检测
			if (_msgItemGoPrefab == null)
			{
				_msgItemGoPrefab = Resources.Load<GameObject>("UIPanel/MsgItem");
			}
			
			
			JsonData historyMsgs = JsonMapper.ToObject(_chatVo.HistoryMsg);
			foreach (JsonData historyMsg in historyMsgs)
			{
				int userId = (int) historyMsg["userId"];
				string content = historyMsg["content"].ToString();
				string time = historyMsg["time"].ToString();
				MsgDO msgDo = new MsgDO();
				msgDo.Content = content;
				msgDo.ReceiveTime = time;
				//判断消息放置左或右
				if (userId == UnityFacade.Instance.ApplicationManager.ActiveUser.UserId)
				{
					msgDo.ActiveAvatar = "right";
				}
				else
				{
					msgDo.ActiveAvatar = "left";
				}

				GameObject msgItemGo = GameObject.Instantiate(_msgItemGoPrefab, v_layoutPos, false);
				MsgItem msgItem = msgItemGo.GetComponent<MsgItem>();
				msgItem.MsgDo = msgDo;
				msgItem.SyncShow();
				
			}
		}
       
	}
}
